/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * 
 * 		Author: tThirday 
 * 		Please report bugs to http://eyecm.com.
 * 		Any problems, please leave messages on http://eyecm.com.
 */
package com.eyecm.connector;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


import org.apache.log4j.Logger;

import com.eyecm.exception.ConnectorException;
import com.eyecm.model.Contact;
import com.eyecm.model.User;

import rath.msnm.BuddyList;
import rath.msnm.MSNMessenger;
import rath.msnm.UserStatus;
import rath.msnm.entity.MsnFriend;

public class MsnConnector extends BaseConnector
{

	private MSNMessenger msn;
	private Logger logger = Logger.getLogger(MsnConnector.class);
	
	public MsnConnector(User user)
	{
		this.user = user;
		msn = new MSNMessenger();
	}

	@Override
	protected void login() throws ConnectorException
	{
		msn.setInitialStatus(UserStatus.OFFLINE);
		msn.login(user.getUsername(), user.getPassword());
	}

	@Override
	protected void logout() throws ConnectorException
	{
		msn.logout();
	}

	
	@Override
	@SuppressWarnings("rawtypes")
	public List<Contact> getContacts() throws ConnectorException
	{
		try
		{
			this.login();
			logger.info("Login as " + user.getUsername() + " succeed.");
			
			List<Contact> contacts = new ArrayList<Contact>();
			BuddyList list = msn.getBuddyGroup().getAllowList();
			for (Iterator iter = list.iterator(); iter.hasNext();)
			{
				MsnFriend friend = (MsnFriend) iter.next();
				contacts.add(new Contact(new String(friend.getFriendlyName()
						.getBytes(), "UTF-8"), friend.getLoginName()));
			}

			this.logout();
			
			logger.info("Get " + user.getUsername() + "'s contacts succeed.");
			return contacts;
		} catch (Exception e)
		{
			throw new ConnectorException(ConnectorInterface.ERR_MSG_UNKNOWN, e);
		}
	}
}
